package com.healthy.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.healthy.entity.YgAdmins;
import com.healthy.entity.YgDocument;
import com.healthy.mapper.YgDocumentMapper;
import com.healthy.service.YgCharpterService;
import com.healthy.util.Dateutil;
import com.healthy.util.FileUtil;
import com.healthy.util.Page;
import com.healthy.util.PropertiesUtil;

@Service
@Transactional
public class YgCharpterServiceImpl implements YgCharpterService{
	
	@Autowired
	private YgDocumentMapper ygDocumentMapper;

	/*
	 * 管理员发布文章
	 */
	@Override
	public JSONObject saveCharpter(HttpServletRequest request, MultipartFile file, String admin_id) {
		JSONObject json = new JSONObject();
        int status = -1;
        String msg = "文件上传失败,请稍后再试";
        // 检测文件是否上传
        if (file.isEmpty()) {
            msg = "提交失败！未选择上传的文件";
            json.put("status", status);
            json.put("msg", msg);
            return json;
        }
        /**
         * 区别在于 当需要判断指定字符串是否为空（""||null）时使用isEmpty
		 * 当有特殊需求 例如空格也算为空，\t\r\n这种默认视为空的可以使用isBlank
		 * 在判断""与null时二者可以互相替换，若有空格isEmpty是false的但是isBlank就是true
         */
        // 检测标题是否为空，标题不可使用空格，用isBlank()判断
        String title = ( StringUtils.isBlank(request.getParameter("title") ) ? null : request.getParameter("title") );
        if (title == null) {
            msg = "提交失败！标题不可为空";
            json.put("status", status);
            json.put("msg", msg);
            return json;
        }
        /**
         * StringUtils.isEmpty()
         * 判断某字符串是否为空，为空的标准是str==null或str.length()==0
         * 对于制表符、换行符、换页符和回车符("\t","\r","\n","\f"):StringUtils.isEmpty()均识为非空字符串
         */
        // 验证文章类型
        String type = ( StringUtils.isEmpty(request.getParameter("type"))  ? null : request.getParameter("type") );
        if (type == null) {
            msg = "提交失败！文章类型不可为空";
            json.put("status", status);
            json.put("msg", msg);
            return json;
        }
        // 验证文章内容
        String content = ( StringUtils.isEmpty(request.getParameter("content"))  ? null : request.getParameter("content") );
        if (content == null) {
            msg = "提交失败！文章内容不可为空";
            json.put("status", status);
            json.put("msg", msg);
            return json;
        }
        // 验证优先级设置
        Integer priority = 0;
        try{
            String priorityStr = ( StringUtils.isEmpty(request.getParameter("priority")) ) ? null : request.getParameter("priority");
            if( priorityStr !=null ) priority = Integer.valueOf(priorityStr);
        }catch (Exception e){
        	e.printStackTrace();
        }
        // 判断资源存放路径是否存在，不存在就创建，即在当前工程目录下创建upload文件夹
        FileUtil.createFileOrPath(request, File.separator + "upload" + File.separator + "charpterimg");
        // 获取文件全名
        String fileOldName = file.getOriginalFilename();
        // 获取文件名前缀
        String filePrefix = FileUtil.getFileNameExcludingEnds(fileOldName);
        // 获取文件后缀
        String fileSuffix = FileUtil.getFileNameEnds(fileOldName);
        // 文件重命名，追加字符: 文件全名_时间.扩展名
        String newFileName;
        try {
            newFileName = filePrefix + "_" + Dateutil.getTimeStampString() + fileSuffix;
        } catch (Exception e) {
            e.printStackTrace();
            newFileName = fileOldName;
        }
        // 文件保存（文件流，保存路径＋文件名）
        String gateWayPath = request.getServletContext().getRealPath("") + File.separator;
        String savePath = "upload" + File.separator + "charpterimg" + File.separator + newFileName;
//        System.out.println(gateWayPath+savePath);
        boolean success = FileUtil.saveFile(file, gateWayPath+savePath);
        // 如果文件上传成功，就把记录写入数据库
        if (success) {
        	YgDocument yg = new YgDocument();
    		yg.setTitle(title);
    		yg.setContent(content);
    		try {
    			yg.setPostTime(Dateutil.getCurrentDateTime());
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
    		yg.setType(type);
    		yg.setPriority(priority);
    		yg.setHead_img(savePath);
    		YgAdmins ya = new YgAdmins();
    		ya.setAid(admin_id);
    		yg.setAdmins(ya);
    		int affectLine = ygDocumentMapper.saveCharpter(yg);
    		if(affectLine > 0){
    			msg = "文章发表成功";
    			status = 1;
    		}else{
    			// 数据入数据库不成功，将上传成功的文件删除
    			FileUtil.deleteFile(gateWayPath+savePath);
    			msg = "文章发表失败，系统繁忙，请稍后再次尝试";
    		}
        }
        json.put("status", status);
        json.put("msg", msg);
        return json;
	}

	/*
	 * 查询某个文章内容
	 */
	@Override
	public JSONObject queryCharpterById(String document_id) {
		JSONObject json = new JSONObject();
		String msg = "查询失败,未搜到符合条件的信息";
		int status = -1;
		if(document_id == null){
			msg = "非法操作，文章id不可为空";
			return json;
		}
		YgDocument yd = ygDocumentMapper.queryCharpterById(document_id);
		if( yd != null){
			json.put("title", yd.getTitle());
			json.put("content", yd.getContent());
			json.put("author", yd.getAdmins().getNickname());
			json.put("postTime", Dateutil.getFormatTimeString(Dateutil.myDateutil, yd.getPostTime()));
			json.put("did", document_id);
			json.put("priority", yd.getPriority());
			json.put("type", yd.getType());
			status = 1;
			msg = "查询成功";
		}
		json.put("status", status);
		json.put("msg", msg);
		return json;
	}

	/*
	 * 修改文章
	 */
	@Override
	public JSONObject updateCharpter(MultipartFile file, HttpServletRequest request, String admin_id) {
		JSONObject json = new JSONObject();
		String msg = "修改文章失败";
		int status = -1;
		// 判断要修改文章的id是否为空
		String did = ( StringUtils.isEmpty(request.getParameter("did") ) ? null : request.getParameter("did") );
		if( did == null ){
			json.put("msg", "文章id不可为空");
			json.put("status", status);
			return json;
		}
		// 判断文章是否是本人发表，否则不可修改
		YgDocument yd = ygDocumentMapper.queryCharpterById(did);
		if( yd == null ){
			json.put("msg", "未找到对应文章或文章已被删除");
			json.put("status", status);
			return json;
		}
		if( ! admin_id.equals(yd.getAdmins().getAid()) ){
			json.put("msg", "非本人操作，文章不可修改");
			json.put("status", status);
			return json;
		}
 		String title = ( StringUtils.isEmpty(request.getParameter("title") ) ? null : request.getParameter("title") );
 		String content = ( StringUtils.isEmpty(request.getParameter("content") ) ? null : request.getParameter("content") );
 		String type = ( StringUtils.isEmpty(request.getParameter("type") ) ? null : request.getParameter("type") );
 		Integer priority = null;
        try{
            String priorityStr = ( StringUtils.isEmpty(request.getParameter("priority")) ) ? null : request.getParameter("priority");
            if( priorityStr !=null ) priority = Integer.valueOf(priorityStr);
        }catch (Exception e){
        	e.printStackTrace();
        }
        YgDocument newYd = new YgDocument();
        // 判断是否上传文件，不上传则使用之前的文件，上传则删除旧文件
        String gateWayPath = request.getServletContext().getRealPath("") + File.separator;
        String savePath = null;
        boolean newFileIn = false;
 		if( ! file.isEmpty() ){
 			
 			// 获取新文件全名
 	        String fileOldName = file.getOriginalFilename();
 	        // 获取新文件名前缀
 	        String filePrefix = FileUtil.getFileNameExcludingEnds(fileOldName);
 	        // 获取新文件后缀
 	        String fileSuffix = FileUtil.getFileNameEnds(fileOldName);
 	        // 文件重命名，追加字符: 文件全名_时间.扩展名
 	        String newFileName;
 	        try {
 	            newFileName = filePrefix + "_" + Dateutil.getTimeStampString() + fileSuffix;
 	        } catch (Exception e) {
 	            e.printStackTrace();
 	            newFileName = fileOldName;
 	        }
 	        // 文件保存（文件流，保存路径＋文件名）
 	        savePath = "upload" + File.separator + "charpterimg" + File.separator + newFileName;
 	        boolean success = FileUtil.saveFile(file, gateWayPath+savePath);
 	        if( success ) newFileIn = true;
 		}
 		// 填充修改对象信息
		newYd.setDid(did);
		// 需要更改的信息
		newYd.setTitle(title);
		newYd.setContent(content);
		newYd.setType(type);
		if( newFileIn ) newYd.setHead_img(savePath);
		newYd.setPriority(priority);
		// 必须填充的属性
		try {
			newYd.setPostTime(Dateutil.getCurrentDateTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int affectLine = ygDocumentMapper.updateCharpter(newYd);
		if(affectLine > 0){
			msg = "文章修改成功";
			status = 1;
			// 修改数据入库成功后才将旧文件删除
			if( newFileIn ) FileUtil.deleteFile(gateWayPath+yd.getHead_img());
		}else{
			// 数据入数据库不成功，将上传的新文件删除，存在则删除，不存在则不执行删除操作
			FileUtil.deleteFile(gateWayPath+savePath);
			msg = "文章修改失败，系统繁忙，请稍后再次尝试";
		}
 		json.put("msg", msg);
		json.put("status", status);
		return json;
	}

	/*
	 * 删除文章
	 */
	@Override
	public JSONObject deleteCharpter(HttpServletRequest request, String document_id, String admin_id) {
		JSONObject json = new JSONObject();
		String msg = "删除文章失败,未找到文章";
		int status = -1;
		// 判断文章是否是本人发表，否则不可修改
		YgDocument yd = ygDocumentMapper.queryCharpterById(document_id);
		if( yd == null ){
			json.put("msg", "未找到对应文章或文章已被删除");
			json.put("status", status);
			return json;
		}
		if( ! admin_id.equals(yd.getAdmins().getAid()) ){
			json.put("msg", "非本人操作，文章不可删除");
			json.put("status", status);
			return json;
		}
		int affectLine = ygDocumentMapper.deleteCharpter(document_id);
		if( affectLine > 0 ){
			String gateWayPath = request.getServletContext().getRealPath("") + File.separator;
			FileUtil.deleteFile(gateWayPath+yd.getHead_img());
			status = 1;
			msg = "文章已删除";
		}
		json.put("msg", msg);
		json.put("status", status);
		return json;
	}

	/*
	 * 管理员查询自己发布的文章，分页
	 */
	@Override
	public JSONObject queryCharptersByAdminId(int pageNum, int pageSize, String admin_id) {
		JSONObject json = new JSONObject();
		String msg = "暂无数据";
		int status = -1;
		// 利用mybatis分页插件拿到分页数据，并获得数据总数totalCount
		PageHelper.startPage(pageNum, pageSize);
		List<YgDocument> list = ygDocumentMapper.queryCharptersByAdminId(admin_id);
		PageInfo<YgDocument> pageInfo = new PageInfo<>(list);
		int total = (int)pageInfo.getTotal();
		if(total > 0){
			// 自己使用对象进行封装
			List<Map<String, Object>> packList = new ArrayList<>();
			Map<String, Object> map = null;
			// 获取项目服务器路径
			String serverip = "";
			try {
	    		String path=this.getClass().getClassLoader().getResource("default.ini").getPath();
		    	File file = new File(path);
				serverip = PropertiesUtil.Find("serverip", file);
			} catch (IOException e) {
				e.printStackTrace();
				json.put("msg", "系统业务繁忙，请稍后再试");
				json.put("status", status);
				return json;
			}
			// 对象集合封装
			for(YgDocument yd:pageInfo.getList()){
				map = new HashMap<>();
				map.put("did", yd.getDid());
				map.put("date", Dateutil.getFormatTimeString(Dateutil.myDateutil, yd.getPostTime()));
				map.put("author", yd.getAdmins().getNickname());
				map.put("title", yd.getTitle());
				map.put("pic_url", serverip + yd.getHead_img());
				packList.add(map);
			}
			// 由于对象比较复杂，可能会含有空集合，下面用自写工具类进行封装
			Page<Map<String, Object>> page = new Page(pageNum, pageSize, packList);
			page.setTotalCount( total );
			json.put("page", page);
			msg = "查询成功，数据返回";
			status = 1;
		}
		json.put("msg", msg);
		json.put("status", 1);
		return json;
	}

	/*
	 * 查询所有文章
	 */
	@Override
	public JSONObject queryAllOfCharpters(int pageNum, int pageSize) {
		JSONObject json = new JSONObject();
		String msg = "暂无数据";
		int status = -1;
		// 利用mybatis分页插件拿到分页数据，并获得数据总数totalCount
		PageHelper.startPage(pageNum, pageSize);
		List<YgDocument> list = ygDocumentMapper.queryAllOfCharpters();
		PageInfo<YgDocument> pageInfo = new PageInfo<>(list);
		int total = (int)pageInfo.getTotal();
		if(total > 0){
			// 自己使用对象进行封装
			List<Map<String, Object>> packList = new ArrayList<>();
			Map<String, Object> map = null;
			// 获取项目服务器路径
			String serverip = "";
			try {
	    		String path=this.getClass().getClassLoader().getResource("default.ini").getPath();
		    	File file = new File(path);
				serverip = PropertiesUtil.Find("serverip", file);
			} catch (IOException e) {
				e.printStackTrace();
				json.put("msg", "系统业务繁忙，请稍后再试");
				json.put("status", status);
				return json;
			}
			// 对象集合封装
			for(YgDocument yd:pageInfo.getList()){
				map = new HashMap<>();
				map.put("did", yd.getDid());
				map.put("date", Dateutil.getFormatTimeString(Dateutil.myDateutil, yd.getPostTime()));
				map.put("author", yd.getAdmins().getNickname());
				map.put("title", yd.getTitle());
				map.put("pic_url", serverip + yd.getHead_img());
				packList.add(map);
			}
			// 由于对象比较复杂，可能会含有空集合，下面用自写工具类进行封装
			Page<Map<String, Object>> page = new Page(pageNum, pageSize, packList);
			page.setTotalCount( total );
			json.put("page", page);
			msg = "查询成功，数据返回";
			status = 1;
		}
		json.put("msg", msg);
		json.put("status", 1);
		return json;
	}

	/*
	 * 按条件查询所有文章
	 */
	@Override
	public JSONObject queryCharptersByCondition(int pageNum, int pageSize, HttpServletRequest request) {
		JSONObject json = new JSONObject();
		String msg = "暂无数据";
		int status = -1;
		// 模糊搜索，下面的变量都允许为空
		String type = StringUtils.isEmpty(request.getParameter("type")) ? null : request.getParameter("type");
		String title = StringUtils.isEmpty(request.getParameter("title")) ? null : request.getParameter("title");
		String content = StringUtils.isEmpty(request.getParameter("content")) ? null : request.getParameter("content");
		String startTime = StringUtils.isEmpty(request.getParameter("startTime")) ? null : request.getParameter("startTime");
		String endTime = StringUtils.isEmpty(request.getParameter("endTime")) ? null : request.getParameter("endTime");
		// 利用mybatis分页插件拿到分页数据，并获得数据总数totalCount
		PageHelper.startPage(pageNum, pageSize);
		List<YgDocument> list = ygDocumentMapper.queryCharptersByCondition(type, title, content, startTime, endTime);
		PageInfo<YgDocument> pageInfo = new PageInfo<>(list);
		int total = (int)pageInfo.getTotal();
		if(total > 0){
			// 自己使用对象进行封装
			List<Map<String, Object>> packList = new ArrayList<>();
			Map<String, Object> map = null;
			// 获取项目服务器路径
			String serverip = "";
			try {
	    		String path=this.getClass().getClassLoader().getResource("default.ini").getPath();
		    	File file = new File(path);
				serverip = PropertiesUtil.Find("serverip", file);
			} catch (IOException e) {
				e.printStackTrace();
				json.put("msg", "系统业务繁忙，请稍后再试");
				json.put("status", status);
				return json;
			}
			// 对象集合封装
			for(YgDocument yd:pageInfo.getList()){
				map = new HashMap<>();
				map.put("did", yd.getDid());
				map.put("date", Dateutil.getFormatTimeString(Dateutil.myDateutil, yd.getPostTime()));
				map.put("author", yd.getAdmins().getNickname());
				map.put("title", yd.getTitle());
				map.put("pic_url", serverip + yd.getHead_img());
				packList.add(map);
			}
			// 由于对象比较复杂，可能会含有空集合，下面用自写工具类进行封装
			Page<Map<String, Object>> page = new Page(pageNum, pageSize, packList);
			page.setTotalCount( total );
			json.put("page", page);
			msg = "查询成功，数据返回";
			status = 1;
		}
		json.put("msg", msg);
		json.put("status", 1);
		return json;
	}

	/*
	 * 查询所有文章分类
	 */
	@Override
	public JSONObject queryAllCharpterTypes() {
		JSONObject json = new JSONObject();
		String msg = "查询失败，请稍后再试";
		int status = -1;
		List<String> typeList = ygDocumentMapper.queryAllCharpterTypes();
		if( typeList.size() > 0 ){
			json.put("list", typeList);
			msg = "数据返回";
			status = 1;
		}
		json.put("status", status);
		json.put("msg", msg);
		return json;
	}
	
}
